﻿using DE_MVC_WyFy.Models.Enities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace DE_MVC_WyFy.Models
{
	public partial class ShoppingCart
	{


		string ShoppingCartId { get; set; }

		public const string CartSessionKey = "CartID";

		public static ShoppingCart GetCart(HttpContextBase context)
		{
			var cart = new ShoppingCart();
			cart.ShoppingCartId = cart.GetCartId(context);
			return cart;
		}

		// Helper method to simplify shopping cart calls
		public static ShoppingCart GetCart(Controller controller)
		{
			return GetCart(controller.HttpContext);
		}

		public void AddToCart(Product prod)
		{
			// Get the matching cart and album instances
			Cart cartItem = null;
			try
			{
				//cartItem = Cart.Objects.Find(c => c.ProdID.Contains(prod.ID) && c.CartID == ShoppingCartId).Single<Cart>();
				//cartItem = Cart.Objects.Find(c => c.ProdID == "17").ToList().Single<Cart>();
				List<Cart> listCart = Cart.Objects.Find(c => c.ProdID.Contains(prod.ID) && c.CartID == ShoppingCartId).ToList();
				if (listCart.Count > 0)
					cartItem = listCart.Single();
			}
			catch (Exception)
			{

			}

			if (cartItem == null)
			{
				// Create a new cart item if no cart item exists
				cartItem = new Cart
				{
					ProdID = prod.ID,
					CartID = ShoppingCartId,
					Quantity = 1,
					DateCreated = DateTime.Now
				};

				Cart.Objects.AddWithIdentity(cartItem);
			}
			else
			{
				// If the item does exist in the cart, then add one to the quantity
				int count = ++cartItem.Quantity;
				Cart.Objects.Update(c => c.RecordID == cartItem.RecordID, c => new Cart
				{
					Quantity = count
				});
			}
		}

		public int RemoveFromCart(int id)
		{
			// Get the cart
			var cartItem = Cart.Objects.GetById(id);

			int itemCount = 0;

			if (cartItem != null)
			{
				if (cartItem.Quantity > 1)
				{
					cartItem.Quantity--;
					itemCount = cartItem.Quantity;
				}
				else
					Cart.Objects.Delete(cartItem);
			}

			return itemCount;
		}

		public void EmptyCart()
		{
			var cartItems = Cart.Objects.Find(c => c.CartID == ShoppingCartId);

			foreach (var cartItem in cartItems)
			{
				Cart.Objects.Delete(cartItem);
			}

		}

		public List<Cart> GetCartItems()
		{
			return Cart.Objects.Find(c => c.CartID == ShoppingCartId).ToList();
		}

		public int GetCount()
		{
			// Get the count of each item in the cart and sum them up
			int? count = (from cartItems in Cart.Objects.All()
						  where cartItems.CartID == ShoppingCartId
						  select (int?)cartItems.Quantity).Sum();

			// Return 0 if all entries are null
			return count ?? 0;
		}

		public float GetTotal()
		{
			// Multiply album price by count of that album to get 
			// the current price for each of those albums in the cart
			// sum all album price totals to get the cart total
			float total = 0;
			foreach (var item in Cart.Objects.Find(c => c.CartID == ShoppingCartId).ToList())
				total += item.Quantity * item.Price;
			return total;
		}

		//public int CreateOrder(Order order)
		//{
		//	float orderTotal = 0;

		//	var cartItems = GetCartItems();

		//	// Iterate over the items in the cart, adding the order details for each
		//	foreach (var item in cartItems)
		//	{
		//		var orderDetail = new OrderDetail
		//		{
		//			ProdID = item.ProdID,
		//			OrderID = order.OrderID,
		//			UnitPrice = Product.Objects.GetById(item.ProdID).Price,
		//			Quantity = item.Quantity
		//		};

		//		// Set the order total of the shopping cart
		//		orderTotal += (item.Quantity * orderDetail.UnitPrice);

		//		OrderDetail..Add(orderDetail);

		//	}

		//	// Set the order's total to the orderTotal count
		//	order.Total = orderTotal;

		//	// Save the order
		//	storeDB.SaveChanges();

		//	// Empty the shopping cart
		//	EmptyCart();

		//	// Return the OrderId as the confirmation number
		//	return order.OrderID;
		//}

		// We're using HttpContextBase to allow access to cookies.
		public string GetCartId(HttpContextBase context)
		{
			if (context.Session[CartSessionKey] == null)
			{
				if (!string.IsNullOrWhiteSpace(context.User.Identity.Name))
				{
					context.Session[CartSessionKey] = context.User.Identity.Name;
				}
				else
				{
					// Generate a new random GUID using System.Guid class
					Guid tempCartId = Guid.NewGuid();

					// Send tempCartId back to client as a cookie
					context.Session[CartSessionKey] = tempCartId.ToString();
				}
			}

			return context.Session[CartSessionKey].ToString();
		}

		// When a user has logged in, migrate their shopping cart to
		// be associated with their username
		public void MigrateCart(string userName)
		{
			var shoppingCart = Cart.Objects.Find(c => c.CartID == ShoppingCartId);

			foreach (Cart item in shoppingCart)
			{
				item.CartID = userName;
			}

		}

		public object Quantity { get; set; }
	}
}